#!/usr/bin/python
# -*- coding: UTF-8 -*-
import socket
import datetime
import platform
import subprocess

_last_ip = None
_last_host_name = None


def get_host_ip():
    global _last_ip
    if _last_ip:
        return _last_ip
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        _last_ip = s.getsockname()[0]
    except Exception as e:
        print("get host ip err e=", e)
    finally:
        s.close()

    return _last_ip


def get_host_name():
    global _last_host_name
    if _last_host_name:
        return _last_host_name
    try:
        _last_host_name = socket.gethostname()
    except:
        pass

    return _last_host_name


def get_utc_time(format):
    timenow = datetime.datetime.utcnow()
    return timenow.strftime(format)


def get_local_time(format):
    timenow = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    return timenow.strftime(format)


def bytes2human(n):
    symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return "%.3f%s" % (value, s)
    return "%sB" % n


def isWindows():
    if platform.system() == "Windows":
        return True

    return False


"""命令执行输出"""


def ShellOutput(command):
    subp = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        encoding="utf-8",
    )
    return subp.communicate()[0]


"""获取文件数据"""


def get_file_data(path):
    f = open(path, "r")
    a = f.read()
    f.close()

    return a
